﻿// jKinect 1.8
if (typeof (window['jKinect']) == 'undefined') {
    (function (window, undefined) {
        var jKinect = new function () {
            this.handlers = [];
            this.askToSwitchTojKinectBrowserHandler;
            this.onKinectReadyHandler;
            this.kinectHost = window.external;
            this.SKELETON_ARRAY = new Array;
            this.SKELETON_ARRAY["Head"] = ["ShoulderCenter"];
            this.SKELETON_ARRAY["ShoulderCenter"] = ["ShoulderLeft", "ShoulderRight", "Spine"];
            this.SKELETON_ARRAY["ShoulderLeft"] = ["ElbowLeft"];
            this.SKELETON_ARRAY["ElbowLeft"] = ["WristLeft"];
            this.SKELETON_ARRAY["WristLeft"] = ["HandLeft"];
            this.SKELETON_ARRAY["ShoulderRight"] = ["ElbowRight"];
            this.SKELETON_ARRAY["ElbowRight"] = ["WristRight"];
            this.SKELETON_ARRAY["WristRight"] = ["HandRight"];
            this.SKELETON_ARRAY["Spine"] = ["HipCenter"];
            this.SKELETON_ARRAY["HipCenter"] = ["HipLeft", "HipRight"];
            this.SKELETON_ARRAY["HipLeft"] = ["KneeLeft"];
            this.SKELETON_ARRAY["KneeLeft"] = ["AnkleLeft"];
            this.SKELETON_ARRAY["AnkleLeft"] = ["FootLeft"];
            this.SKELETON_ARRAY["HipRight"] = ["KneeRight"];
            this.SKELETON_ARRAY["KneeRight"] = ["AnkleRight"];
            this.SKELETON_ARRAY["AnkleRight"] = ["FootRight"];

            this.initKinect = function (arg1,
                arg2,
                arg3,
				arg4
                ) {
                var config = {};
                var askToSwitchTojKinectBrowserHandler;
                var onKinectReadyHandler;
                if (typeof (arg1) != "object") {
                    // old parsing method with all parameters flatten
                    config["useSkeletonStream"] = arg1;
                    config["eventModel"] = arg2;
                    askToSwitchTojKinectBrowserHandler = arg3;
                    onKinectReadyHandler = arg4;
                }
                else {
                    // parsing method for unique config var
                    config = arg1;
                    askToSwitchTojKinectBrowserHandler = arg2;
                    onKinectReadyHandler = arg3;
                }

                if (typeof (config) == "undefined" || config == null) config = {};
                this.askToSwitchTojKinectBrowserHandler = askToSwitchTojKinectBrowserHandler;
                if (jKinect.isBrowserKinectCompliant()) {
                    if (typeof (config["useSkeletonStream"]) == "undefined") config["useSkeletonStream"] = true;
                    if (typeof (config["eventModel"]) == "undefined") config["eventModel"] = true;
                    if (typeof (config["useInteractionStream"]) == "undefined") config["useInteractionStream"] = true;
                    if (typeof (onKinectReadyHandler) == "undefined" || onKinectReadyHandler == null)
                        alert("jKinect initialisation error.\r\nNo OnKinectReady handler has been defined.");
                    this.onKinectReadyHandler = onKinectReadyHandler;
                    try {
                        this.kinectHost.InitKinect(config);
                    }
                    catch (e) {
                    }
                }
            };
            this.bind = function (eventName, jsHandler) {
                this.handlers[eventName] = jsHandler;
                try {
                    this.kinectHost.Bind(eventName);
                }
                catch (e) {
                }
            };

            this.unbind = function (eventName) {
                this.handlers[eventName] = undefined;
                delete this.handlers[eventName];
                try {
                    this.kinectHost.Unbind(eventName);
                }
                catch (e) {
                }
            };

            this.trigger = function (eventName, args) {
                this.handlers[eventName](args);
            }

            this.accelerometerGetCurrentReading = function () {
                return this.parseJSON(this.kinectHost.AccelerometerGetCurrentReading());
            };
            this.setSeatedMode = function (active) {
                return this.kinectHost.SetSeatedMode(active);
            };
            this.setNearMode = function (active) {
                return this.kinectHost.SetNearMode(active);
            };
            var preventReentrance = false;
            this.getNextSkeletonFrame = function () {
                if (preventReentrance) return;
                preventReentrance = true;
                try {
                    this.kinectHost.GetNextSkeletonFrame();
                }
                catch (e) {
                }
                preventReentrance = false;
            }
            this.callbackFromInjector = function (eventName, isJSON, arg0, arg1, arg2, arg3, arg4) {
                if (eventName == "OnKinectReady") {
                    this.onKinectReadyHandler();
                }
                else {
                    if (isJSON) {
                        this.handlers[eventName](this.parseJSON(arg0));
                    }
                    else
                        this.handlers[eventName](arg0, arg1, arg2, arg3, arg4);
                }
            }

            this.displayParseJSONAlert = true;
            // Utils
            this.parseJSON = function (json) {
                if (typeof (json) == "string" && json.indexOf("{") == 0) {
                    var obj = eval('(' + json + ')');
                    obj.json = json;
                    return obj;
                }
                else {
                    if (this.displayParseJSONAlert == true) {
                        this.displayParseJSONAlert = false;
                        //alert("Developer advice, Kinect event arguments are already deserialized.\r\nPlease, stop calling jKinect.parseJSON.");
                    }
                    return json;
                }
            };

            this.distance = function (joint1Position, joint2Position) {
                var num = joint1Position.X - joint2Position.X;
                var num2 = joint1Position.Y - joint2Position.Y;
                var num3 = joint1Position.Z - joint2Position.Z;
                var num4 = num * num + num2 * num2 + num3 * num3;
                return Math.sqrt(num4);
            }

            this.barycentric = function (joint1Position, joint2Position) {
                var result = new function () {
                    this.X = (joint1Position.X + joint2Position.X) / 2.0,
					this.Y = (joint1Position.Y + joint2Position.Y) / 2.0,
					this.Z = (joint1Position.Z + joint2Position.Z) / 2.0
                };
                return result;
            }

            this.scaleTo = function (jointPosition, pixelMaxWidth, pixelMaxHeight, originalAmplitudeX, originalAmplitudeY) {
                if (originalAmplitudeX == null) originalAmplitudeX = 1.0;
                if (originalAmplitudeY == null) originalAmplitudeY = 1.0;
                var scaledJoint = new function () {
                    this.X = jKinect.scale(pixelMaxWidth, originalAmplitudeX, jointPosition.X);
                    this.Y = jKinect.scale(pixelMaxHeight, originalAmplitudeY, -jointPosition.Y);
                    this.Z = jointPosition.Z;
                    this.W = jointPosition.W;
                };
                return scaledJoint;
            }

            this.scale = function (maxPixel, originalAmplitude, position) {
                var scaled = maxPixel / originalAmplitude / 2.0 * position + (maxPixel / 2.0);
                if (scaled > maxPixel) {
                    return maxPixel;
                }
                if (scaled < 0) {
                    return 0.0;
                }
                return scaled;
            }

            this.isBrowserKinectCompliant = function () {
                try {
                    this.kinectHost.GetVersion().indexOf("jKinect");
                    return true;
                }
                catch (e) {
                    if (typeof (this.askToSwitchTojKinectBrowserHandler) == "undefined" || this.askToSwitchTojKinectBrowserHandler == null) {
                        var divStartWithJKinectBrowser = document.body.appendChild(document.createElement("div"));
                        divStartWithJKinectBrowser.id = "startWithJKinectBrowser";
                        divStartWithJKinectBrowser.style.cssText = "position:absolute;top:0px;left:0px;font-family:tahoma;background-color:yellow;text-align:center;width:100%;";
                        divStartWithJKinectBrowser.innerHTML = "Launch <b><a href='http://jkinect.com/jKinectBrowser.application?url=" + encodeURI(document.location) + "'>jKinectWebBrowser</a></b> to improve your experience";
                    }
                    else {
                        this.askToSwitchTojKinectBrowserHandler();
                    }
                    return false;
                }
            }

            this.writeObject = function (o, prefix) {
                if (typeof (prefix) == "undefined") prefix = "";
                var serialized = "";
                for (property in o) {
                    serialized += prefix + property + ": " + o[property] + "<br/>";
                    if (typeof (o[property]) == "object") {
                        serialized += this.writeObject(o[property], prefix + "&nbsp;");
                    }
                }
                return serialized;
            }
        }
        window.jKinect = jKinect;

    })(window);

    // IE will invoke this method
    // (IE can't invoke object method)
    window.jKinect_Callback = function (eventName, isJSON, arg0, arg1, arg2, arg3, arg4) {
        jKinect.callbackFromInjector(eventName, isJSON, arg0, arg1, arg2, arg3, arg4);
    }

}